<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检查类型" prop="findDangerCount">
        <treeselect style="width: 260px" v-model="queryParams.checkType" :options="deptOptions"
          :default-expand-level="100" placeholder="请选择作检查类型" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['check:check:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['check:check:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['check:check:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['check:check:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="检查任务名称" align="center" prop="checkTaskName" />
      <el-table-column label="检查类型" align="center" prop="checkTypeName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag effect="dark" :color="scope.row.status == '1'
              ? rgb1
              : scope.row.status == '2'
                ? rgb2
                : scope.row.status == '3'
                  ? rgb3
                  : rgb4
            " style="border: 0">
            <dict-tag :options="dict.type.check_status" :value="scope.row.status" />
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="检查人数" align="center" prop="rummagerCount" /> -->
      <el-table-column label="计划检查时间" align="center" prop="planCheckTime" />
      <el-table-column label="完成检查时间" align="center" prop="complateCheckTime" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.complateCheckTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质量问题数" align="center" prop="hiddenDangerSum" />
      <el-table-column label="质量问题整改情况" align="center" prop="hiddenAbarbeitung" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="检查项目id" align="center" prop="projectId" />-->
      <!--      <el-table-column label="检查项目" align="center" prop="checkProject">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.check_project" :value="scope.row.checkProject"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="检查人员" align="center" prop="checkPeople" />-->
      <!--      <el-table-column label="检查说明" align="center" prop="checkMessage" />-->
      <!--      <el-table-column label="发现隐患数" align="center" prop="findDangerCount" />-->
      <!--      <el-table-column label="现场照片" align="center" prop="secnePhoto" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <image-preview :src="scope.row.secnePhoto" :width="50" :height="50"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="LookUpdate(scope.row)"
            v-hasPermi="['check:check:edit']">查看</el-button>
          <el-button size="mini" type="text" v-if="scope.row.status =='1'" icon="el-icon-refresh-left" @click="cancelTask(scope.row)">取消任务</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['check:check:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['check:check:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目自检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :close-on-click-modal="false">
      <div v-if="title == '项目自检查看'">
        <el-tabs v-model="activeNameData">
          <el-tab-pane label="检查概括" name="first">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="任务类型:" prop="checkType">
                {{ form.checkTypeName }}
              </el-form-item>
              <el-form-item label="任务名称:" prop="checkTaskName">
                {{ form.checkTaskName }}
              </el-form-item>
              <el-form-item label="计划检查时间:" prop="planCheckTime">
                {{ form.planCheckTime }}
              </el-form-item>
              <!-- <el-form-item label="检查依据:" prop="checkProject">
                <template slot-scope="scope"> -->
              <!-- <dict-tag
                    :options="dict.type.check_project"
                    :value="scope.row.checkProject"
                  /> -->
              <!-- {{ scope.row }}
                </template>
              </el-form-item> -->
              <el-form-item label="发现质量问题数:" prop="findDangerCount">
                {{ form.findDangerCount }}
              </el-form-item>
              <el-form-item label="检查说明:" prop="checkMessage">
                {{ form.checkMessage }}
              </el-form-item>
              <el-form-item label="现场照片:" prop="secnePhoto">
                <image-preview v-if="form.secnePhoto" :src="form.secnePhoto" :width="50" :height="50" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="检查记录" name="second">
            <el-table v-loading="loading" :data="recordList">
              质量问题名称、检查类型、问题级别、整改人、复查人、整改期限、整改截止时间
              <el-table-column label="质量问题描述" align="center" prop="questionDesc" />
              <el-table-column label="检查类型" align="center" prop="checkTypeName" />
              <el-table-column label="问题级别" align="center" prop="questionLevel">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.list_quality_level" :value="scope.row.questionLevel" />
                </template>
              </el-table-column>
              <el-table-column label="整改人" align="center" prop="revisePeopleName" />
              <el-table-column label="复查人" align="center" prop="reviewUserName" />
              <el-table-column label="整改期限" align="center" prop="rectificationDeadlineStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.list_quality_rectification_deadline_status" :value="scope.row.rectificationDeadlineStatus" />
                </template>
              </el-table-column>
              <el-table-column label="整改截止时间" align="center" prop="reviseTheDates" />
              <!-- <el-table-column label="序号" align="center" prop="id" />
              <el-table-column label="质量问题状态" align="center" prop="hiddenDangerStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.biz_check_result" :value="scope.row.hiddenDangerStatus" />
                </template>
              </el-table-column>
              <el-table-column label="检查时间" align="center" prop="checkTime" width="180">
                <template slot-scope="scope">
                  <span>{{
                    parseTime(scope.row.checkTime, "{y}-{m}-{d}")
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="检查人" align="center" prop="checkPeopleName">
              </el-table-column>
              <el-table-column label="整改期限" align="center" prop="reviseTheDates" width="180">
                <template slot-scope="scope">
                  <span>{{
                    parseTime(scope.row.reviseTheDates, "{y}-{m}-{d}")
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="整改人" align="center" prop="revisePeople" />
              <el-table-column label="质量问题内容" align="center" prop="hiddenMessage" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-view" @click="lookRecord(scope.row)"
                    v-hasPermi="['record:record:edit']">质量问题详情</el-button>
                </template>
              </el-table-column> -->
            </el-table>
            <pagination v-show="recordtotal > 0" :total="recordtotal" :page.sync="recordQueryParams.pageNum"
              :limit.sync="recordQueryParams.pageSize" @pagination="getlistRecord" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else>
        <el-form ref="form" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="检查项目:" prop="projectId">
            <el-input disabled v-model="queryParams.name" placeholder="请输入检查项目id" />
          </el-form-item>
          <el-form-item label="检查类型:" prop="checkType">
            <treeselect v-model="form.checkType" :options="deptOptions" :default-expand-level="100"
              placeholder="请选择作检查类型" />
          </el-form-item>
          <el-form-item label="任务名称:" prop="checkTaskName">
            <el-input v-model="form.checkTaskName" placeholder="请输入检查任务名称" />
          </el-form-item>
          <!-- <el-form-item label="检查项目:" prop="checkProject">
            <el-radio-group v-model="form.checkProject">
              <el-radio
                v-for="dict in dict.type.check_project"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="计划检查时间:" prop="planCheckTime">
            <el-date-picker v-model="form.planCheckTime" type="daterange" range-separator="-" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="检查人员:" prop="checkPeople">


            <el-select v-model="form.checkPeople" placeholder="请选择检查人员">
              <el-option v-for="item in formList.revisePeopleList" :key="item.userId" :value="item.userName"
                :label="item.nickName"></el-option>
            </el-select>
            <!-- <el-input v-model="form.checkPeople" placeholder="请输入检查人员" ></el-input> -->
          </el-form-item>
          <el-form-item label="检查说明:" prop="checkMessage">
            <el-input v-model="form.checkMessage" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <!-- <el-form-item label="现场照片" prop="secnePhoto">
          <image-upload v-model="form.secnePhoto"/>
        </el-form-item> -->
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog width="45%" title="隐患详情" :visible.sync="innerVisible" append-to-body>
        <DialogLook :id="id"></DialogLook>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  listCheck,
  getCheck,
  delCheck,
  addCheck,
  updateCheck,
  treeselect,
  lookRecordData,
} from "@/api/biz/check/check";
import { getRevisePeople, } from "@/api/biz/ledger/ledger";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listRecord } from "@/api/biz/record/record";
import { endTask } from "@/views/quality/myTask/api";
export default {
  name: "Check",
  dicts: ["check_status", "biz_check_result","list_quality_rectification_deadline_status","list_quality_level"],
  components: {
    Treeselect,
  },
  data() {
    return {
      formList: { revisePeopleList: [] },
      id: null,
      firstData: "first",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      recordtotal: 0,
      recordQueryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
      },
      // 项目自检表格数据
      checkList: [],
      // 项目自检-检查记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkTaskName: null,
        checkType: null,
        checkTypeName: null,
        status: null,
        rummagerCount: null,
        planCheckTime: null,
        startTime: null,
        endTime: null,
        complateCheckTime: null,
        hiddenDangerSum: null,
        hiddenAbarbeitung: null,
        projectId: this.$store.state.app.selectData,
        checkProject: null,
        checkPeople: null,
        checkMessage: null,
        findDangerCount: null,
        secnePhoto: null,
      },
      // 表单参数
      form: {},
      // 部门树选项
      deptOptions: [],
      typeNoData: {
        checkTypeNo: null,
      },
      // 表单校验
      rules: {
        planCheckTime: [
          { required: true, message: "计划检查时间不能为空", trigger: "blur" },
        ],
        checkType: [
          { required: true, message: "检查类型不能为空", trigger: "blur" },
        ],
        checkTaskName: [
          { required: true, message: "检查任务名称不能为空", trigger: "blur" },
        ],
        // checkPeople: [
        //   { required: true, message: "检查人员", trigger: "blur" },
        // ],
      },
      rgb1: "rgb(147, 210, 243)",
      rgb2: "rgb(255, 191, 107)",
      rgb3: "rgb(162, 239, 77)",
      rgb4: "rgb(144, 147, 153)",
      activeNameData: "first",
      innerVisible: false,
      // 隐患详情
      lookRecordDataList: {
        bizProjectCheck: {
          checkTaskName: null,
        },
        bizProjectCheckRecord: {
          riskLevel: null,
          hiddenMessage: null,
          supplement: null,
          checkType: null,
          hiddenLevel: null,
          subpackageUnit: null,
          accidentHidden: null,
          revisePeople: null,
          notifier: null,
          reviseTheDates: null,
          reviseRequire: null,
          photo: null,
        },
      },
    };
  },
  watch: {
    app: {
      handler(newVal, oldVal) {
        this.queryParams.projectId = newVal.selectData;
        this.queryParams.name = newVal.selectUpdata.name;
        this.getList();
      },
      deep: true,
    },
  },
  computed: {
    ...mapState(["app"]),
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      treeselect(this.typeNoData).then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询项目自检列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then((response) => {
        this.checkList = response.rows;
        for (let i = 0; i < this.checkList.length; i++) {
          this.checkList[i].id = this.checkList[i].id;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        checkTaskName: null,
        checkType: null,
        checkTypeName: null,
        status: null,
        rummagerCount: null,
        planCheckTime: null,
        startTime: null,
        endTime: null,
        complateCheckTime: null,
        hiddenDangerSum: null,
        hiddenAbarbeitung: null,
        projectId: null,
        checkProject: null,
        checkPeople: null,
        checkMessage: null,
        findDangerCount: null,
        secnePhoto: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        name: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.checkType = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.projectId == null) {
        this.$message({
          message: "请选择项目部后再点击!",
          type: "warning",
        });
      } else {
        getRevisePeople(this.queryParams).then((data) => {
          this.formList.revisePeopleList = data.rows;
        });
        this.open = true;
        this.title = "添加项目自检";
        (this.queryParams.name = this.$store.state.app.selectUpdata.name),
          this.reset();
        this.form.checkProject = "1";
      }
    },
    /** 查看按钮操作 */
    LookUpdate(row) {
      this.reset();
      this.recordQueryParams.id = row.id;
      getCheck(row.id).then((response) => {
        this.form = response.data;
        this.title = "项目自检查看";
      });
      this.getlistRecord();
      this.open = true;
    },
    // 弹框 检查记录
    getlistRecord() {
      // listRecord(this.recordQueryParams).then((response) => {
      lookRecordData({...this.recordQueryParams, fileId: this.recordQueryParams.id}).then((response) => {
        this.recordList = response.rows;
        this.recordtotal = response.total;
        this.loading = false;
      });
    },
    //取消任务
    async cancelTask(row) {
      let data = {
        id: row.id,
        status: 4,
        projectId: this.projectId
      }
      const res = await endTask(data)
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: '任务取消成功'
        })
      }
      this.getList(true)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCheck(id).then((response) => {
        this.form = response.data;
        if (this.form.planCheckTime != null) {
          this.form.planCheckTime = [];
          this.form.planCheckTime.push(response.data.startTime);
          this.form.planCheckTime.push(response.data.endTime);
        }
        this.open = true;
        this.title = "编辑项目自检";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.title == "项目自检查看") {
        this.reset();
        this.open = false;
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.startTime = this.form.planCheckTime[0];
            this.form.endTime = this.form.planCheckTime[1];
            this.form.planCheckTime = null;
            if (this.form.id != null) {
              updateCheck(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
              });
            } else {
              this.form.projectId = this.queryParams.projectId;
              addCheck(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
              });
            }
            this.open = false;
            this.getList();
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除项目自检编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCheck(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "check/check/export",
        {
          ...this.queryParams,
        },
        `check_${new Date().getTime()}.xlsx`
      );
    },
    //隐患详情
    lookRecord(row) {
      // lookRecordData(row.id).then(({ data }) => {
      //   this.lookRecordDataList = data;
      //   this.lookRecordDataList.bizProjectCheckRecord.attachList.forEach((item) => {
      //         item.name = process.env.VUE_APP_MINIO_BASE_API +
      //         "/" +
      //         item.bucket +
      //         "/" +
      //         item.name;
      //   });
      //   this.lookRecordDataList.bizRectifyReviews.forEach((items) => {
      //     items.attachList.forEach((item) => {
      //           item.name = process.env.VUE_APP_MINIO_BASE_API +
      //           "/" +
      //           item.bucket +
      //           "/" +
      //           item.name;
      //     });
      //   })
      // });
      this.id = row.id;
      this.innerVisible = true;
      // console.log(this.lookRecordDataList.bizProjectCheckRecord);
    },
  },
};
</script>
<style scoped>
.spanStyle {
  margin: 0 10px;
}
</style>